#!/bin/bash
echo "Executing script by: LIUCHANGXING 24055060146"
echo "-----------------------------------------"
MY_GENDER="M"
if [ "$MY_GENDER" = "M" ]; then
    gender_full_name="male(M)"
elif [ "$MY_GENDER" = "F" ]; then
    gender_full_name="female(F)"
else
    echo "Error: Invalid gender! Please set MY_GENDER to 'M' or 'F'."
    exit 1
fi
SOURCE_DIR="students"
if [ ! -d "$SOURCE_DIR" ]; then
    echo "Error: Directory '$SOURCE_DIR' not found! Please run create_student_files.sh first."
    exit 1
fi
cd "$SOURCE_DIR" || exit 1
total_average_score=0.0
student_count=0
echo "Calculating average score for all '$MY_GENDER' students..."
for file in *.txt; do
    if [ ! -f "$file" ]; then
        continue
    fi
    file_gender=$(grep "^gender: " "$file" | awk '{print $2}')
    if [ "$file_gender" = "$MY_GENDER" ]; then
        student_average=$(grep "^average: " "$file" | awk '{print $2}')
                total_average_score=$(echo "scale=2; $total_average_score + $student_average" | bc)
        student_count=$(( student_count + 1 ))
        echo "Processed: $file (average: $student_average)"
    fi
done
if [ $student_count -eq 0 ]; then
    final_average="0.0"
    echo "-----------------------------------------"
    echo "No students with gender '$MY_GENDER' found!"
else
    final_average=$(echo "scale=2; $total_average_score / $student_count" | bc)
    echo "-----------------------------------------"
    echo "Total students found: $student_count"
fi
echo "Average score of $gender_full_name: $final_average"
exit 0
